package org.ym.basic;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.ym.basic.config.SnowflakeConfig;
import org.ym.tools.StringPool;

import java.lang.management.ManagementFactory;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 雪花算法生成ID
 * @author ym
 * @date 2022-06-09 21:53:11
 */
@Slf4j
public  class FileSnowflakeIdWorker {
    /**
     * 日期格式
     */
    private static final String TIME_FORMAT_TYPE = "yyyy-MM-dd HH:mm:ss";

    /**
     * 获取起始时间
     * @return Time
     */
    private static long getTime() {
        Date date = new Date();
        SimpleDateFormat format = new SimpleDateFormat(TIME_FORMAT_TYPE);
        try {
            date = format.parse("2023-01-01 00:00:00");
        } catch (ParseException e) {
            e.printStackTrace();
            // doNothing
        }
        return date.getTime();
    }

    // ==============================Fields==================

    /**
     * 开始时间截
     */
    private static final long START_TIME = getTime();

    /**
     * 机器id所占的位数
     */
    private static final long WORKER_ID_BITS = 5L;

    /**
     * 数据标识id所占的位数
     */
    private static final long DATACENTER_ID_BITS = 5L;

    /**
     * 支持的最大机器id，结果是31 (这个移位算法可以很快的计算出几位二进制数所能表示的最大十进制数)
     */
    private static final long MAX_WORKER_ID = -1L ^ (-1L << WORKER_ID_BITS);

    /**
     * 支持的最大数据标识id，结果是31
     */
    private static final long MAX_DATACENTER_ID = -1L ^ (-1L << DATACENTER_ID_BITS);

    /**
     * 序列在id中占的位数
     */
    private static final long SEQUENCE_BITS = 12L;

    /**
     * 机器ID向左移12位
     */
    private static final long WORKER_ID_SHIFT = SEQUENCE_BITS;

    /**
     * 数据标识id向左移17位(12+5)
     */
    private static final long DATACENTER_ID_SHIFT = SEQUENCE_BITS + WORKER_ID_BITS;

    /**
     * 时间截向左移22位(5+5+12)
     */
    private static final long TIMESTAMP_LEFT_SHIFT = SEQUENCE_BITS + WORKER_ID_BITS + DATACENTER_ID_BITS;

    /**
     * 生成序列的掩码，这里为4095 (0b111111111111=0xfff=4095)
     */
    private static final long SEQUENCE_MASK = -1L ^ (-1L << SEQUENCE_BITS);

    /**
     * 工作机器ID(0~31)
     */
    private final long workerId;

    /**
     * 数据中心ID(0~31)
     */
    private final long dataCenterId;

    /**
     * 毫秒内序列(0~4095)
     */
    private long sequence = 0L;

    /**
     * 上次生成ID的时间截
     */
    private long lastTimestamp = -1L;

    /**
     * 获取 maxWorkerId
     */
    protected static long getMaxWorkerId(long datacenterId, long maxWorkerId) {
        StringBuilder mPid = new StringBuilder();
        mPid.append(datacenterId);
        //获取jvm进程信息
        String name = ManagementFactory.getRuntimeMXBean().getName();
        if (StringUtils.isNotBlank(name)) {
            /*
             * 获取进程PID
             */
            mPid.append(name.split(StringPool.AT)[0]);
        }
        /*
         * MAC + PID 的 hashcode 获取16个低位
         */
        return (mPid.toString().hashCode() & 0xffff) % (maxWorkerId + 1);
    }

    /**
     * 数据中心
     * @param maxDatacenterId
     * @return
     */
    protected static long getDatacenterId(long maxDatacenterId) {
        long id = 0L;
        try {
            //获取本机(或者服务器ip地址)
            //DESKTOP-123SDAD/192.168.1.87
            InetAddress ip = InetAddress.getLocalHost();
            NetworkInterface network = NetworkInterface.getByInetAddress(ip);
            //一般不是null会进入else
            if (network == null) {
                id = 1L;
            } else {
                //获取物理网卡地址
                byte[] mac = network.getHardwareAddress();
                if (null != mac) {
                    id = ((0x000000FF & (long) mac[mac.length - 2]) | (0x0000FF00 & (((long) mac[mac.length - 1]) << 8))) >> 6;
                    id = id % (maxDatacenterId + 1);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return id;
    }

    //==============================Constructors====================
    /**
     * 构造函数
     */
    public FileSnowflakeIdWorker() {
        SnowflakeConfig config = AppUtils.getBean(SnowflakeConfig.class);
        if (config.workId > MAX_WORKER_ID || config.workId < 0) {
            throw new IllegalArgumentException(String.format("worker Id can't be greater than %d or less than 0", MAX_WORKER_ID));
        }
        if (config.dataCenterId > MAX_DATACENTER_ID || config.dataCenterId < 0) {
            throw new IllegalArgumentException(String.format("dataCenter Id can't be greater than %d or less than 0", MAX_DATACENTER_ID));
        }
        this.workerId = config.workId;
        this.dataCenterId = config.dataCenterId;
    }
    // ==============================Methods=================================

    /**
     * 获得下一个ID (该方法是线程安全的)
     *
     * @return SnowflakeId
     */
    public synchronized long nextId() {
        long timestamp = timeGen();

        //如果当前时间小于上一次ID生成的时间戳，说明系统时钟回退过这个时候应当抛出异常
        if (timestamp < lastTimestamp) {
            throw new SnowFlakeIdWorkerRuntimeException(
                    String.format("Clock moved backwards.  Refusing to generate id for %d milliseconds", lastTimestamp - timestamp));
        }

        //如果是同一时间生成的，则进行毫秒内序列
        if (lastTimestamp == timestamp) {
            sequence = (sequence + 1) & SEQUENCE_MASK;
            //毫秒内序列溢出
            if (sequence == 0) {
                //阻塞到下一个毫秒,获得新的时间戳
                timestamp = tilNextMillis(lastTimestamp);
            }
        }
        //时间戳改变，毫秒内序列重置
        else {
            sequence = 0L;
        }

        //上次生成ID的时间截
        lastTimestamp = timestamp;

        //移位并通过或运算拼到一起组成64位的ID
        return ((timestamp - START_TIME) << TIMESTAMP_LEFT_SHIFT)
                | (dataCenterId << DATACENTER_ID_SHIFT)
                | (workerId << WORKER_ID_SHIFT)
                | sequence;
    }

    /**
     * 阻塞到下一个毫秒，直到获得新的时间戳
     *
     * @param lastTimestamp 上次生成ID的时间截
     * @return 当前时间戳
     */
    protected long tilNextMillis(long lastTimestamp) {
        long timestamp = timeGen();
        while (timestamp <= lastTimestamp) {
            timestamp = timeGen();
        }
        return timestamp;
    }

    /**
     * 返回以毫秒为单位的当前时间
     *
     * @return 当前时间(毫秒)
     */
    protected long timeGen() {
        return System.currentTimeMillis();
    }

    /**
     * 默认为0的快速生成ID，单机模式
     */
    private static final FileSnowflakeIdWorker SNOWFLAKE_ID_WORKER = new FileSnowflakeIdWorker();

    /**
     * 默认的快速生成ID，单机模式
     */
    public static long genIdByLong() {
        return SNOWFLAKE_ID_WORKER.nextId();
    }

    /**
     * 默认的快速生成ID，单机模式
     */
    public static String genId() {
        return String.valueOf(genIdByLong());
    }

    //==============================Test=============================================

    private static class SnowFlakeIdWorkerRuntimeException extends RuntimeException{
        public SnowFlakeIdWorkerRuntimeException() {
        }

        public SnowFlakeIdWorkerRuntimeException(String message) {
            super(message);
        }

        public SnowFlakeIdWorkerRuntimeException(String message, Throwable cause) {
            super(message, cause);
        }

        public SnowFlakeIdWorkerRuntimeException(Throwable cause) {
            super(cause);
        }

        public SnowFlakeIdWorkerRuntimeException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
            super(message, cause, enableSuppression, writableStackTrace);
        }
    }
}